"""Game engine classes/function."""

__author__ = 'Josh Oosterman'

import os
import pygame
import pygame.gfxdraw
import pygame.image
import pygame.transform

from potv import geom
from potv.game import game


def LoadImage(filepath, origin=None):
  """Loads an image from disk, or returns null if it's not available."""
  try:
    return Image(filepath, origin)
  except ValueError:
    return None


class Image(object):
  """Wraps a pygame image."""
  IMAGE_PATH = 'resources/images'

  def __init__(self, arg, origin=None):
    if hasattr(arg, 'set_colorkey'):
      self.image = arg
    else:
      fpath = os.path.join(self.IMAGE_PATH, arg)
      if not os.path.exists(fpath):
        raise ValueError('File %s does note exist' % fpath)
      img = pygame.image.load(fpath).convert()
      img.set_colorkey((255, 0, 255), pygame.RLEACCEL)
      self.image = img
    if origin is None:
      origin = geom.Vector(0,0)
    self.origin = origin

  def CenterOrigin(self):
    """Sets the origin of the image to its center."""
    self.origin = geom.Vector(
        self.image.get_rect().width / 2, self.image.get_rect().height / 2)

  def Rotated(self, angle):
    """Returns a copy of the image rotated by some angle."""
    unrotated = self.image
    rotated = pygame.transform.rotate(unrotated, angle)
    unrotated_center = geom.Vector(
        unrotated.get_rect().width / 2,
        unrotated.get_rect().height / 2)
    rotated_center = geom.Vector(
        rotated.get_rect().width / 2,
        rotated.get_rect().height / 2)
    v1 = self.origin - unrotated_center
    a, m = v1.ToAngleMagnitude()
    v2 = geom.Vector()
    v2.FromAngleMagnitude(a + angle, m)
    v3 = rotated_center - v2
    return Image(rotated, v3)
